package Controller

import (
	"back_go/DAO/gorm"
	"back_go/DAO/gorm/GormModel"
	"back_go/Response"
	"back_go/Util"
	"github.com/gin-gonic/gin"
	"math"
	"strconv"
	"time"
)

func GetListTagList(c *gin.Context) {
	db := gorm.Db
	var prodTag []GormModel.TzProdTag
	db.Find(&prodTag).Where("status = 1").Order("seq desc")
	c.JSON(200, gin.H{
		"code":    "00000",
		"msg":     "ok",
		"data":    prodTag,
		"success": true,
	})

}
func GetProdTagByPage(c *gin.Context) {
	// 解析分页参数
	currentStr := c.Query("current")
	sizeStr := c.Query("size")
	statusStr := c.Query("status")
	title := c.Query("title")

	// 将字符串类型的分页参数转换为整数
	current, err := strconv.Atoi(currentStr)
	if err != nil {
		current = 1 // 默认当前页为 1
	}
	size, err := strconv.Atoi(sizeStr)
	if err != nil {
		size = 10 // 默认每页显示 10 条记录
	}

	// 解析状态参数
	var status *int
	if statusStr != "" {
		statusInt, err := strconv.Atoi(statusStr)
		if err == nil {
			status = &statusInt
		}
	}

	// 绑定查询参数到 TzProdTag 结构体
	var prodTag GormModel.TzProdTag
	_ = c.ShouldBindQuery(&prodTag)

	db := gorm.Db
	// 构建查询
	query := db.Model(&GormModel.TzProdTag{})

	// 根据 TzProdTag 中的字段动态构建查询条件
	if status != nil {
		query = query.Where("status = ?", *status)
	}
	if title != "" {
		query = query.Where("title LIKE ?", "%"+title+"%")
	}

	// 按 Seq 和 CreateTime 降序排序
	query = query.Order("seq DESC, create_time DESC")

	// 计算偏移量
	offset := (current - 1) * size

	// 执行分页查询
	var prodTags []GormModel.TzProdTag
	var total int64
	if err := query.Count(&total).Error; err != nil {
		c.JSON(200, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Fail:      true,
			Success:   false,
		})
		return
	}
	if err := query.Offset(offset).Limit(size).Find(&prodTags).Error; err != nil {
		c.JSON(200, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Fail:      true,
			Success:   false,
		})
		return
	}

	// 返回分页结果
	c.JSON(200, Response.ResponseBody{
		Code: "00000",
		Data: PageParam1[GormModel.TzProdTag]{
			Current: current,
			Total:   total,
			Size:    size,
			Records: prodTags,
			Pages:   int(math.Ceil(float64(total) / float64(size))),
		},
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}

func GetProdTagById(c *gin.Context) {
	id := c.Param("tagId")

	db := gorm.Db
	var prodTag GormModel.TzProdTag
	db.Where("id = ?", id).Find(&prodTag)
	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Data:      prodTag,
		Msg:       "ok",
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Fail:      false,
		Success:   true,
	})
}

func UpdateProdTag(c *gin.Context) {
	var prodTag GormModel.TzProdTag
	_ = c.ShouldBindJSON(&prodTag)
	db := gorm.Db.Begin()
	now := time.Now()
	prodTag.UpdateTime = &now
	err := db.Save(&prodTag).Error
	defer func() {
		if r := recover(); r != nil {
			db.Rollback()
			c.JSON(200, Response.ResponseBody{
				Code:    "A00005",
				Data:    nil,
				Success: true,
				Msg:     "服务器出了点小差",
			})
		} else if err != nil {
			db.Rollback()
		} else {
			db.Commit()
		}
	}()

	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Data:      prodTag,
		Msg:       "ok",
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Fail:      false,
		Success:   true,
	})
}

func SaveProdTag(c *gin.Context) {
	var prodTag GormModel.TzProdTag
	err := c.ShouldBindJSON(&prodTag)
	db := gorm.Db.Begin()
	now := time.Now()
	prodTag.UpdateTime = &now
	prodTag.CreateTime = &now
	defer func() {
		if r := recover(); r != nil {
			db.Rollback()
			c.JSON(200, Response.ResponseBody{
				Code:    "A00005",
				Data:    nil,
				Success: true,
				Msg:     "服务器出了点小差",
			})
		} else if err != nil {
			db.Rollback()
		} else {
			db.Commit()
		}
	}()
	var list []GormModel.TzProdTag
	//prodTagService.list(new LambdaQueryWrapper<ProdTag>().like(ProdTag::getTitle, prodTag.getTitle()));
	db.Where("title =?", prodTag.Title).Find(&list)
	if Util.SliceIsNotEmpty(list) {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00005",
			Data:    nil,
			Success: true,
			Msg:     "标签名称已存在，不能添加相同的标签",
		})
		return
	}
	prodTag.IsDefault = 0
	prodTag.ProdCount = 0
	tmpTime := time.Now()
	prodTag.CreateTime = &tmpTime
	prodTag.UpdateTime = &tmpTime
	prodTag.ShopID = 1

	err = db.Save(&prodTag).Error

	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Data:      true,
		Msg:       nil,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Fail:      false,
		Success:   true,
	})
}

func DelProdTag(c *gin.Context) {
	id := c.Param("tagId")
	db := gorm.Db.Begin()
	var err error
	defer func() {
		if r := recover(); r != nil {
			db.Rollback()
			c.JSON(200, Response.ResponseBody{
				Code:    "A00005",
				Data:    nil,
				Success: true,
				Msg:     "服务器出了点小差",
			})
		} else if err != nil {
			db.Rollback()
			c.JSON(200, Response.ResponseBody{
				Code:    "A00005",
				Data:    nil,
				Success: false,
				Msg:     "删除操作失败",
			})
		} else {
			db.Commit()
		}
	}()
	var prodTag GormModel.TzProdTag
	db.Where("id =?", id).Find(&prodTag)
	if prodTag.IsDefault != 0 {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00005",
			Data:    nil,
			Success: true,
			Msg:     "默认标签不能删除",
		})
		return
	}
	err = db.Where("id =?", id).Delete(&prodTag).Error
	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Data:      true,
		Msg:       nil,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Fail:      false,
		Success:   true,
	})
}
